package com.forever.okhttpdemo.thread;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class LoginAsyncTask extends AsyncTask<String, Void, byte[]> {
	private Context context;

	public LoginAsyncTask(Context context) {
		this.context = context;

	}

	@Override
	protected byte[] doInBackground(String... params) {
		RequestBody formBody = new FormEncodingBuilder().add("username", "wy")
				.add("password", "123").build();

		byte[] mbyte = null;

		try {
			OkHttpClient client = new OkHttpClient();
			Request request = new Request.Builder().url(params[0])
					.post(formBody).build();
			Response response = client.newCall(request).execute();

			if (response.isSuccessful()) {
				mbyte = response.body().bytes();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return mbyte;
	}

	@Override
	protected void onPostExecute(byte[] result) {
		super.onPostExecute(result);
		if (result != null) {

			Toast.makeText(context, new String(result), 0).show();
		} else {
			Toast.makeText(context, "失败", 0).show();
		}
	}

}
